#!/usr/bin/env python

import os
import email
import smtplib
import hashlib
import urllib
import urllib2


def search(metadata):
	"""
	Search VirusTotal for hashes in metadata
	Updates metadata with a link to results if successful
	Returns True/False depending on success
	"""
	
	# Build the POST request
	url = 'http://www.virustotal.com/vt/en/consultamd5'
	post_data = { 'hash' : metadata['sha1'] }
	encoded_data = urllib.urlencode(post_data)
	request = urllib2.Request(url, encoded_data)
	
	# Make the request and capture the response
	try:
		response = urllib2.urlopen(request)
	except URLError, e:
		print "Error: " + e.strerror
		print "Searching for existing VirusTotal reports failed..."
		return False

	# VirusTotal always respond with a 303 redirect
	# If the 303 contains "/analysis/[hash]" then it found an existing report
	# If the 303 contains /buscaHash.html?notfound then it didn't find one
	result = response.geturl()

	if "analisis" in result:
		print "VirusTotal: Found existing report"
		metadata['VirusTotal'] = response.geturl()
		return True
	else:
		#print "VirusTotal has not seen this file before"
		return False

def submit(filepath, FROM_ADDR, SMTP_HOST, SMTP_PORT, SMTP_USER=None, SMTP_PASS=None):
	"""
	E-mails the file to VirusTotal for analysis
	"""

	#print 'Sending to VirusTotal for analysis...'
	
	TO_ADDR = "scan@virustotal.com"
	
	try:
		filehandle = open(filepath, "rb")
		data = filehandle.read()
	except IOError, e:
		print "Error: " + e.strerror
		print "Could not open " + filepath + "for reading"
		sys.exit(1)
		
	filehandle.close()
	
	msg = email.MIMEMultipart.MIMEMultipart()
	msg['From'] = FROM_ADDR
	msg['To'] = TO_ADDR
	msg['Date'] = email.Utils.formatdate()
	msg['Subject'] = 'SCAN'

	part = email.MIMEBase.MIMEBase('application', 'octet-stream')
	part.set_payload(data)
	email.Encoders.encode_base64(part)
	part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filepath))
	msg.attach(part)
	
	smtp = smtplib.SMTP(host=SMTP_HOST, port=SMTP_PORT)
	if SMTP_USER and SMTP_PASS:
		smtp.starttls()
		smtp.login(SMTP_USER, SMTP_PASS)
	smtp.sendmail(FROM_ADDR, TO_ADDR, msg.as_string())
	smtp.close()
	
	print "VirusTotal: Check e-mail for results"
	
if __name__ == "__main__":
	import sys, hashlib
	
	filepath = sys.argv[1]
	filehandle = open(filepath, "rb")
	data = filehandle.read()
	filehandle.close()
	
	metadata = {}
	metadata['sha1'] = hashlib.sha1(data).hexdigest()
		
	if not search(metadata):
		submit(filepath, "malware@cryptocity.net", "mail.cryptocity.net", 587, None, None)
